<template>
  <Layout :showHome="false" :showH="false">
    <div class="container">
      <div class="header">
        <van-icon name="arrow-left" @click="$router.go(-1)" />
        <h2>绑定银行卡</h2>
        <van-icon name="" />
      </div>
      <van-form @submit="onSubmit">
        <van-field
          v-model="cardNumber"
          name="银行卡号"
          placeholder="请输入银行卡号"
          :rules="[{ required: true, message: '请填写银行卡号' },{ validator, message: '请输入正确卡号' }]"
          size="big"
        />
        <van-field
          v-model="phone"
          name="手机号"
          placeholder="请输入手机号"
          :rules="[{ required: true, message: '请填写手机号' },{ pattern, message: '请输入正确手机号' }]"
          size="big"
        />
        <div style="margin: 16px" class="btn">
          <van-button round block type="info" native-type="submit" color="#f56e00" :disabled="flag">{{text}}</van-button>
        </div>
      </van-form>
    </div>
  </Layout>
</template>

<script>
import { Dialog } from 'vant'
import { editUserApi, editActiveApi, UserApi, editMessageApi } from '@/apis/signApi'

export default {
  data () {
    return {
      cardNumber: '',
      flag: false,
      text: '提交信息',
      phone: '',
      pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
      message: [],
      obj: {}
    }
  },
  methods: {
    validator (val) {
      return /^([1-9]{1})(\d{11}|\d{15}|\d{16}|\d{17}|\d{18})$/.test(val)
    },
    async onSubmit (values) {
      /* console.log('submit', values) */
      const userId = this.$store.getters['common/userId']
      await editActiveApi(userId, 2)
      await editUserApi(userId, {
        phone: this.phone,
        bankCard: this.cardNumber
      })
      this.flag = true
      this.text = '已提交'
      Dialog.alert(
        {
          title: '绑定银行卡成功！',
          message: '',
          theme: 'round-button'
        }).then(() => {
        this.$router.push('/home')
      })
      let objId = 0
      const res = await UserApi(userId)
      this.message = res.message
      if (this.message.length === 0) {
        objId = 0
      } else {
        objId = Number(this.message[this.message.length - 1].id)
      }
      this.obj = {
        id: objId + 1,
        title: '消息通知',
        desc: '绑定银行卡成功！请继续完成注册流程，与平台进行签约！',
        status: 0
      }
      this.message.push(this.obj)
      await editMessageApi(userId, this.message)
    }
  },
  components: {
    [Dialog.Component.name]: Dialog.Component
  }
}
</script>

<style lang="less" scoped>
@import "../../style/common.less";

.container {
  padding: 0 20px;
  .header {
    padding-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    h2 {
      font-size: 1rem;
      font-weight: normal;
      margin: 0;
    }
  }
  .van-form{
    margin-top: 30px;
    .btn{
      margin-top: 30px !important;
    }
  }
}
</style>
